package com.karina.visualization.chart.component;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Timer;

public class UpdateManager {

	private final int TIME = 100;

	@SuppressWarnings("rawtypes")
	private List<UpdateableObject> availableObjects = new ArrayList<UpdateableObject>();

	@SuppressWarnings("rawtypes")
	private List<UpdateableObject> updatingObjects = new ArrayList<UpdateableObject>();

	private boolean updating = false;

	private boolean enable = true;

	private final Timer timer = new Timer() {

		@Override
		public void run() {
			updating = true;
			update();
		}
	};

	public void enable() {
		enable = true;
		// availableObjects.clear();
		// updatingObjects.clear();
		startTimer();
	}

	public void disable() {
		enable = false;
		timer.cancel();
	}

	@SuppressWarnings("rawtypes")
	public void registerComponent(UpdateableObject object) {
		if (!object.isInvisible() || availableObjects.contains(object)
				|| updatingObjects.contains(object))
			return;

		availableObjects.add(object);

		if (!updating)
			startTimer();
		else {
			resetTimer();
		}
	}

	@SuppressWarnings("rawtypes")
	public void startTimer() {
		if (!enable || availableObjects.size() == 0)
			return;
		updating = true;
		updatingObjects.addAll(availableObjects);
		availableObjects = new ArrayList<UpdateableObject>();
		timer.schedule(TIME);
	}

	/**
	 * reset the timer which need to be restart
	 * 
	 */
	public void resetTimer() {

		if (updating) {
			updating = false;
			timer.cancel();
		}

		startTimer();
	}

	@SuppressWarnings("rawtypes")
	protected void update() {
		for (UpdateableObject component : updatingObjects) {
			component.update();
		}
		updatingObjects = new ArrayList<UpdateableObject>();
		updating = false;
		startTimer();
	}

}
